package ru.hh.team02.chat.messaging;

import java.util.List;
import java.util.Set;

import ru.hh.team02.chat.client.Client;
import ru.hh.team02.chat.server.ChatServer;

/**
 * class responsible for macro sending logic. current version - one queue with
 * messages per active client
 */
public class SendingService {
    /**
     * send personal message
     * @param message - message text
     * @param recepientName
     */
    public void trySendPersonalMessage(String message, String recepientName) {
        if (!ChatServer.dbService.clientExists(recepientName)) {
            return;
        }

        // put message to database
        int id = ChatServer.dbService.putNewPersonalMessageIntoDatabase(message, recepientName);

        sendPersonalMessage(id, message, recepientName);
    }

    public void sendUndeliveredMessages(String clientName) {
        List<MessageDbEntry> messages = ChatServer.dbService.getAllUndeliveredMessagesToTheClient(clientName);

        for (MessageDbEntry entry : messages) {
            sendPersonalMessage(entry.ID, entry.Message, entry.Recepient);
        }
    }

    // put it to recepients sending queue
    private void sendPersonalMessage(int id, String message, String recepientName) {
        if (ChatServer.REGISTRY.hasClientWithName(recepientName)) {
            Client recepient = ChatServer.REGISTRY.getClientByName(recepientName);
            recepient.add(new Message(personalMessageProtocol(id, message), true));
        }
    }

    /**
     * Put message to all personal queues of people, who are in the same room as
     * sender
     *
     * @param text
     *            Message text
     * @param senderName
     *            Sender name
     */
    public void sendMessageToRoom(String text, String senderName) {
        String room = ChatServer.REGISTRY.getClientRoom(senderName);
        Set<Client> recepients = ChatServer.REGISTRY.getClientsFromRoom(room);

        for (Client recepient : recepients) {
            recepient.add(new Message(text, false));
        }

    }

    private String personalMessageProtocol(int id, String message) {
        return " " + id + " " + message;
    }
}
